package cn.idietrade.idietradegoodsorder8003.demo.controller;


import cn.idietrade.common.pojo.SecondOrder;
import cn.idietrade.common.utils.EmptyUtils;
import cn.idietrade.common.utils.ReturnResultData;
import cn.idietrade.idietradegoodsorder8003.demo.service.GoodsOrderService;
import cn.idietrade.idietradegoodsorder8003.demo.service.OrderGoodsService;
import cn.idietrade.idietradegoodsorder8003.demo.service.OrderService;
import cn.idietrade.idietradegoodsorder8003.demo.service.PayService;
import cn.idietrade.idietradegoodsorder8003.demo.utils.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class PayController {
    @Resource
    private PayService payService;

    @Resource
    private OrderService orderService;



    @RequestMapping("/pay")
    @Transactional
    public ReturnResultData buy(HttpServletResponse resp, SecondOrder secondOrder, String goodsIds, String nums, String subject){
        ReturnResultData resultData = new ReturnResultData<>();
        try {
            String alipay = payService.alipay(resp, secondOrder, goodsIds, nums, subject);
            if (EmptyUtils.isNotEmpty(alipay)){
                resultData.setCode(1);
                resultData.setMessage("成功");
                resultData.setData(alipay);
            }else{
                resultData.setCode(0);
                resultData.setMessage("失败");
                resultData.setData(alipay);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  resultData;
    }

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request){
        try {
        //支付宝支付成功之后返回
        Map<String, String[]> paramMap = request.getParameterMap();
        Map<String, String> param = new HashMap<String, String>();
        for(String key:paramMap.keySet()){
            Object [] obj = paramMap.get(key);
            String value = "";
            for(Object object:obj){
                value = object +",";
                value = value.substring(0,value.length()-1);
            }
            param.put(key,value);
        }

        //对支付宝的返回结果进行验签，判断是否成功

            boolean flag = AlipaySignature.rsaCheckV1(param, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type);
            int orderId=0;
            if (flag){
                String outTradeNo = param.get("out_trade_no");
                orderId = orderService.queryOrderId(outTradeNo);
                //成功后通过订单id修改支付状态为待发货
                orderService.updateOrState(orderId,2);
                return "付款成功30秒内没有自动关闭，请手动关闭页面刷新订单页面.....";
            }else {
                orderService.updateOrState(orderId,3);
                return "付款失败30秒内没有自动关闭，请手动关闭页面刷新订单页面.....";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "付款失败30秒内没有自动关闭，请手动关闭页面刷新订单页面.....";
    }

    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request){
        Map<String, String[]> paramMap = request.getParameterMap();
        return "异步支付成功";
    }


    /**
     * 支付宝退款
     */
    @PostMapping("/refund")
    public String alipayRefund(String outTradeNo,String tradeNo,
                                        String refundAmount,String subject) {
        boolean result = false;
        try {
            result = payService.alipayRefund(outTradeNo, tradeNo, refundAmount, subject);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (result){
            return "退款成功";
        }else {
            return "退款失败";
        }
    }

    // 退费查询
    @PostMapping("/RefundSelect")
    public String alipayRefundCallback(String outRequestNo,String tradeNo) {
        boolean result = false;
        result = payService.alipayRefundSelect(outRequestNo, tradeNo);
        if (result){
            return "退款成功";
        }else {
            return "退款失败";
        }
    }


}
